import unittest
from unittest import mock
from engine_server.parser.config_parser import ConfigParser
from engine_server.config.base import ServerConfig, BaseConfig, IConfig


class MockVLLMConfig(BaseConfig):
    def __init__(self, server_config: ServerConfig):
        self.server_config = server_config
        self.convert_called = False
        self.validate_called = False
    
    def convert(self):
        self.convert_called = True
    
    def validate(self):
        self.validate_called = True


class TestConfigParser(unittest.TestCase):
    
    def setUp(self):
        self.mock_server_config = mock.MagicMock(spec=ServerConfig)
        self.mock_server_config.engine_type = "vllm"
    
    @mock.patch('engine_server.parser.config_parser.ConfigParser._import_vllm_config')
    def test_init(self, mock_import_vllm_config):
        mock_import_vllm_config.return_value = MockVLLMConfig
        
        parser = ConfigParser(self.mock_server_config)
        
        self.assertEqual(parser.server_config, self.mock_server_config)
        self.assertIn("vllm", parser._config_class_map)
        self.assertEqual(parser._config_class_map["vllm"], MockVLLMConfig)
        mock_import_vllm_config.assert_called_once()
    
    @mock.patch('engine_server.parser.config_parser.ConfigParser._import_vllm_config')
    def test_parse_valid_engine_type(self, mock_import_vllm_config):
        mock_import_vllm_config.return_value = MockVLLMConfig
        
        parser = ConfigParser(self.mock_server_config)
        
        result = parser.parse()
        
        self.assertIsInstance(result, MockVLLMConfig)
        self.assertTrue(result.convert_called)
        self.assertTrue(result.validate_called)
        self.assertEqual(result.server_config, self.mock_server_config)
    
    @mock.patch('engine_server.parser.config_parser.ConfigParser._import_vllm_config')
    def test_parse_unsupported_engine_type(self, mock_import_vllm_config):
        mock_import_vllm_config.return_value = MockVLLMConfig
        
        self.mock_server_config.engine_type = "unsupported_engine"
        
        parser = ConfigParser(self.mock_server_config)
        
        with self.assertRaises(ValueError) as context:
            parser.parse()
        
        self.assertIn("Unsupported engine type: unsupported_engine", str(context.exception))
        self.assertIn("vllm", str(context.exception))
    
    @mock.patch('engine_server.parser.config_parser.ConfigParser._import_vllm_config')
    def test_import_vllm_config(self, mock_import_vllm_config):
        mock_vllm_config = mock.MagicMock()
        mock_import_vllm_config.return_value = mock_vllm_config
        
        parser = ConfigParser(self.mock_server_config)
        
        mock_import_vllm_config.assert_called_once()
        self.assertEqual(parser._config_class_map["vllm"], mock_vllm_config)


if __name__ == '__main__':
    unittest.main()